package my.engine.utils;

import org.hibernate.cfg.AnnotationConfiguration;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.servlet.*;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

import my.engine.objects.entities.Property;

/**
 * User: emikolenko
 * Date: 07.03.2008
 * Time: 11:46:39
 */
public class EntityManagerFilter implements Filter {

    private static EntityManagerFactory entityManagerFactory;

    private static ThreadLocal<EntityManager> managerThreadLocal = new ThreadLocal<EntityManager>();

    public void init(FilterConfig filterConfig) throws ServletException {
        entityManagerFactory = Persistence.createEntityManagerFactory("engine");

        SettingsUtil.checkDefaultSettings();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        EntityManager em = entityManagerFactory.createEntityManager();
        managerThreadLocal.set(em);

        try {
            filterChain.doFilter(servletRequest, servletResponse);
            em.close();
        } finally {
            managerThreadLocal.remove();
        }
    }

    public void destroy() {
        //entityManagerFactory.close();
    }

    public static EntityManager getEntityManager() {
        return managerThreadLocal.get();
    }

    public static EntityManager createEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

}
